package de.tv.weatherox;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class TestServlet extends javax.servlet.http.HttpServlet {
    public static final Logger LOGGER = Logger.getLogger(TestServlet.class.getName());

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        handleRequest(request, response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        handleRequest(request, response);
    }

    @SuppressWarnings("unchecked")
    protected void handleRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws IOException {
        WeatherForecastBuilder builder = WeatherForecastBuilder.create(new LiveWetterochsPage());
        EntityManager em = null;
        List<Forecast> forecasts;
        try {
            em = EMF.get().createEntityManager();
            for (Forecast f : builder.getDailyForecasts()) {
                Query query = em.createQuery("SELECT f FROM Forecast f WHERE f.id = :id");
                query.setParameter("id", f.getId());
                List test = query.getResultList();
                if (test.size() == 0) {
                    LOGGER.info("Creating " + f.getId());
                    em.getTransaction().begin();
                    em.persist(f);
                    em.getTransaction().commit();
                } else {
                    LOGGER.info("Updating " + f.getId());
                }
            }
            Query q = em.createQuery("SELECT f FROM Forecast f ORDER BY f.date desc");
            q.setMaxResults(7);
            forecasts = q.getResultList();
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").excludeFieldsWithoutExposeAnnotation().create();
            response.getWriter().append(gson.toJson(forecasts));

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
